package com.uxsino.simo.indicator.retractor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

// directly pass JSONArray, no retract

public class JSONArrayNoRetractor extends ListValueRetractor {
    private static Logger logger = LoggerFactory.getLogger(JSONArrayNoRetractor.class);

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        JSONArray array;
        if (obj instanceof JSONArray) {
            array = (JSONArray) obj;
        } else if (obj instanceof JSONObject) {
            array = new JSONArray();
            array.add(obj);
        } else {
            logger.error("input obj is not JSONArray OR JSONObject");
            return null;
        }
        ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
        for (Object object : array) {

            Map<String, Object> temp = new HashMap<String, Object>();

            JSONObject json = (JSONObject) object;

            for (ColumnEntry entry : columnEntries) {

                Object value = json.get(entry.index);

                if (value == null) {

                    logger.warn("column index out of range:{} . value is null!", entry.index);
                }

                temp.put(entry.field.getName(), value);
            }

            records.add(temp);
        }

        return records;
    }
}
